<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElDialog, ElMessage, ElEmpty } from 'element-plus'
import { Check, Edit, Delete, Plus } from '@element-plus/icons-vue'
import ajax from "../main.ts"

interface ModelConfig {
  id: number
  name: string
  apiKey: string
  apiUrl: string
  model: string
}

interface ApiResponse<T> {
  code: number
  msg: string
  data: T
}

const props = defineProps<{
  visible: boolean
}>()

const emit = defineEmits(['update:visible'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const models = ref<ModelConfig[]>([])
const selectedModel = ref<ModelConfig | null>(null)
const isEditing = ref(false)
const isAdding = ref(false)
const isLoading = ref(false)
const isChecking = ref(false)

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    fetchModels()
    // 重置所有状态
    selectedModel.value = null
    isEditing.value = false
    isAdding.value = false
    isChecking.value = false
  }
})

// 获取模型列表
const fetchModels = async () => {
  try {
    isLoading.value = true
    const response = await ajax.get('getModel/') as ApiResponse<ApiResponse<ModelConfig[]>>
    if (response.data.code !== 200) {
      ElMessage.error(response.data.msg)
      return
    }
    models.value = response.data.data
  } catch (error) {
    console.error(error)
    ElMessage.error('获取模型列表失败')
  } finally {
    isLoading.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
  // 重置所有状态
  selectedModel.value = null
  isEditing.value = false
  isAdding.value = false
  isChecking.value = false
}

const handleModelSelect = (model: ModelConfig) => {
  selectedModel.value = model
  isEditing.value = false
  isAdding.value = false
}

// 检查API密钥
const handleCheckApiKey = async (model: ModelConfig) => {
  if (isChecking.value) return
  
  try {
    isChecking.value = true
    const response = await ajax.post('checkModel/', {
      id: model.id,
      name: model.name,
      apiKey: model.apiKey,
      apiUrl: model.apiUrl,
      model: model.model
    }) as ApiResponse<ApiResponse<null>>
    
    if (response.data.code !== 200) {
      ElMessage.error(response.data.msg || 'API密钥验证失败')
      return
    }
    ElMessage.success('API密钥验证成功')
  } catch (error) {
    console.error(error)
    ElMessage.error('API密钥验证失败，请检查网络连接')
  } finally {
    isChecking.value = false
  }
}

const handleEdit = () => {
  isEditing.value = true
}

const handleAdd = () => {
  isAdding.value = true
  selectedModel.value = {
    id: models.value.length + 1,
    name: '',
    apiKey: '',
    apiUrl: '',
    model: ''
  }
}

// 保存模型配置
const handleSave = async () => {
  if (!selectedModel.value) return
  
  try {
    const url = isAdding.value ? 'addModel/' : 'updateModel/'
    const response = await ajax.post(url, selectedModel.value) as ApiResponse<ApiResponse<null>>
    
    if (response.data.code !== 200) {
      ElMessage.error(response.data.msg)
      return
    }
    
    ElMessage.success(isAdding.value ? '添加成功' : '保存成功')
    isEditing.value = false
    isAdding.value = false
    await fetchModels() // 刷新列表
  } catch (error) {
    console.error(error)
    ElMessage.error(isAdding.value ? '添加失败' : '保存失败')
  }
}

// 删除模型
const handleDelete = async (model: ModelConfig) => {
  try {
    const response = await ajax.post('deleteModel/', { id: model.id }) as ApiResponse<ApiResponse<null>>
    
    if (response.data.code !== 200) {
      ElMessage.error(response.data.msg)
      return
    }
    
    if (selectedModel.value?.id === model.id) {
      selectedModel.value = null
    }
    ElMessage.success('删除成功')
    await fetchModels() // 刷新列表
  } catch (error) {
    console.error(error)
    ElMessage.error('删除失败')
  }
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="模型服务配置"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
    class="model-service-dialog"
  >
    <div class="model-service-container">
      <!-- 左侧模型列表 -->
      <div class="model-list">
        <div class="model-list-header">
          <h3>模型列表</h3>
          <button class="add-model-btn" @click="handleAdd" :disabled="isLoading">
            <el-icon><Plus /></el-icon>
            <span>添加模型</span>
          </button>
        </div>
        <div class="model-items">
          <div v-if="isLoading" class="loading-state">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>
          <template v-else>
            <div
              v-for="model in models"
              :key="model.id"
              class="model-item"
              :class="{ 'selected': selectedModel?.id === model.id }"
              @click="handleModelSelect(model)"
            >
              <span class="model-name">{{ model.name }}</span>
              <div class="model-actions">
                <el-icon class="action-icon edit-icon" @click.stop="handleEdit">
                  <Edit />
                </el-icon>
                <el-icon class="action-icon delete-icon" @click.stop="handleDelete(model)">
                  <Delete />
                </el-icon>
              </div>
            </div>
          </template>
        </div>
      </div>

      <!-- 右侧配置信息 -->
      <div class="model-config">
        <template v-if="selectedModel">
          <div class="config-header">
            <h3>{{ isAdding ? '添加模型' : (isEditing ? '编辑模型' : '模型配置') }}</h3>
            <button v-if="!isEditing && !isAdding" class="edit-btn" @click="handleEdit">
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </button>
          </div>

          <div class="config-form">
            <div class="form-item">
              <label>模型名称</label>
              <input
                v-model="selectedModel.name"
                :disabled="!isEditing && !isAdding"
                placeholder="请输入模型名称"
              />
            </div>
            <div class="form-item">
              <label>API密钥</label>
              <div class="api-key-input">
                <input
                  v-model="selectedModel.apiKey"
                  :disabled="!isEditing && !isAdding"
                  placeholder="请输入API密钥"
                  type="password"
                />
                <button
                  class="check-btn"
                  :disabled="!isEditing && !isAdding || isChecking"
                  @click="handleCheckApiKey(selectedModel)"
                >
                  <el-icon v-if="!isChecking"><Check /></el-icon>
                  <el-icon v-else class="is-loading"><Loading /></el-icon>
                  <span>{{ isChecking ? '检查中...' : '检查' }}</span>
                </button>
              </div>
            </div>
            <div class="form-item">
              <label>API地址</label>
              <input
                v-model="selectedModel.apiUrl"
                :disabled="!isEditing && !isAdding"
                placeholder="请输入API地址"
              />
            </div>
            <div class="form-item">
              <label>模型</label>
              <input
                v-model="selectedModel.model"
                :disabled="!isEditing && !isAdding"
                placeholder="请输入模型"
              />
            </div>
          </div>

          <div v-if="isEditing || isAdding" class="config-actions">
            <button class="cancel-btn" @click="isEditing = false; isAdding = false">取消</button>
            <button class="save-btn" @click="handleSave">保存</button>
          </div>
        </template>
        <div v-else class="no-selection">
          <el-empty
            description="请选择一个模型"
            :image-size="120"
          >
            <template #image>
              <el-icon :size="48" color="#6366f1"><Edit /></el-icon>
            </template>
          </el-empty>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<style scoped>
.model-service-dialog {
  :deep(.el-dialog) {
    background: rgba(255, 255, 255, 0.98);
    backdrop-filter: blur(16px);
    -webkit-backdrop-filter: blur(16px);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(0, 0, 0, 0.05);
  }

  :deep(.el-dialog__header) {
    padding: 20px;
    margin: 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  }

  :deep(.el-dialog__title) {
    font-size: 18px;
    font-weight: 600;
    color: #1a1a1a;
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.model-service-container {
  display: flex;
  height: 600px;
}

.model-list {
  width: 280px;
  border-right: 1px solid rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
}

.model-list-header {
  padding: 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.model-list-header h3 {
  margin: 0;
  font-size: 16px;
  color: #1a1a1a;
  font-weight: 600;
}

.add-model-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.add-model-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.2);
}

.model-items {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.model-item {
  padding: 12px 16px;
  background: white;
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.model-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-color: rgba(99, 102, 241, 0.2);
}

.model-item.selected {
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.1), rgba(139, 92, 246, 0.1));
  border-color: rgba(99, 102, 241, 0.3);
}

.model-name {
  font-size: 14px;
  font-weight: 500;
  color: #1a1a1a;
}

.model-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.model-item:hover .model-actions {
  opacity: 1;
}

.action-icon {
  font-size: 16px;
  color: #6b7280;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.action-icon:hover {
  background: rgba(0, 0, 0, 0.05);
}

.edit-icon:hover {
  color: #6366f1;
}

.delete-icon:hover {
  color: #ef4444;
}

.model-config {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.config-header h3 {
  margin: 0;
  font-size: 16px;
  color: #1a1a1a;
  font-weight: 600;
}

.edit-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  background: rgba(99, 102, 241, 0.1);
  color: #6366f1;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.edit-btn:hover {
  background: rgba(99, 102, 241, 0.2);
}

.config-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-size: 14px;
  color: #4b5563;
  font-weight: 500;
}

.form-item input {
  padding: 10px 12px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.form-item input:focus {
  outline: none;
  border-color: #6366f1;
  box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
}

.form-item input:disabled {
  background: #f3f4f6;
  cursor: not-allowed;
}

.api-key-input {
  display: flex;
  gap: 8px;
}

.api-key-input input {
  flex: 1;
}

.check-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 0 12px;
  background: rgba(99, 102, 241, 0.1);
  color: #6366f1;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.check-btn:hover:not(:disabled) {
  background: rgba(99, 102, 241, 0.2);
}

.check-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.config-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

.cancel-btn {
  padding: 8px 16px;
  background: transparent;
  color: #4b5563;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: rgba(0, 0, 0, 0.05);
}

.save-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.save-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.2);
}

.no-selection {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

:deep(.el-empty__description) {
  margin-top: 16px;
  color: #6366f1;
  font-size: 14px;
}

:deep(.el-empty__image) {
  color: #6366f1;
}

.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 20px;
  color: #6366f1;
}

.loading-state .el-icon {
  font-size: 20px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.check-btn .is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 